//task_doorInstallation.js
const util = require("../../utils/util.js");

const app = getApp()

Page({
  data: {
    order_id: '',
    // 选中的任务类型
    selectedTask_type: "设备维护",
    // 任务时间
    taskTime: "",
    // 住宅位置
    taskAddress: "",
    // 问题列表
    questionList: [],
    // 问题描述
    questionDesc: "",
    questionSelectIndex: 0,
    questionId: "",
    questionTypeName:"",
    // 维护费用
    matenanceCost: "",
    // 备注信息
    memoInfo: "",
    // 存放本地图片路径
    tempFilePaths: [],
    // 存放图片上传路径
    imagesUpload: [],
    // 滤网建材
    filterBuildArray: [],
  },
  onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.setData({
      order_id: options.id,
      taskTime: options.time,
      taskAddress: options.address
    })

    // 获取物料数组
    this.refreshNewData();
    this.$wuxToast = app.wux(this).$wuxToast;
  },
  // 选择物料类型
  bindMaterielChange: function (e) {
    var value = e.detail.value;

    var questionIdStr = this.data.questionList[value].id;
    var questionTypeNameStr = this.data.questionList[value].name;
    // 修改全局变量
    this.setData({
      questionSelectIndex: value,
      questionId: questionIdStr,
      questionTypeName: questionTypeNameStr
    })
  },
  // 问题描述
  inputQuestionDesc: function (e) {
    this.setData({
      questionDesc: e.detail.value
    })
  },
  // 维护费用
  inputMatenanceCost: function (e) {
    this.setData({
      matenanceCost: e.detail.value
    })
  },
  // 备注信息
  inputMemoInfo: function (e) {
    this.setData({
      memoInfo: e.detail.value
    })
  },
  // 查看上传图片
  uploadImageShowAction: function (event) {
    var index = event.currentTarget.dataset.index;
    var that = this;
    var currentUrl = that.data.imagesUpload[index];

    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: that.data.imagesUpload // 需要预览的图片http链接列表
    })
  },
  // 选择图片
  chooseimage: function () {
    var _this = this;
    var imagePaths = this.data.tempFilePaths;
    var uploadImagePaths = this.data.imagesUpload;

    wx.chooseImage({
      count: 9, // 默认9  
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        // 新选择图片的本地路径
        var filePathsArray = res.tempFilePaths;
        wx.showToast({
          title: '上传中...',
          icon: 'loading',
          mask: true,
          duration: 20000000
        });

        filePathsArray.forEach(function (item, index) {
          wx.uploadFile({
            url: app.globalData.BaseURL + '/fileUpload/image',
            filePath: item,
            name: 'file',
            success: function (res) {
              var state = JSON.parse(res.data).state;
              if (state == "success") {
                var url = JSON.parse(res.data).url;
                // 存放图片上传路径数组加1️
                uploadImagePaths.push(url);
                _this.setData({
                  imagesUpload: uploadImagePaths
                })
                // 存放本地图片路径数组加1️
                imagePaths.push(item);
                _this.setData({
                  tempFilePaths: imagePaths
                })
                if (index == filePathsArray.length - 1) {
                  wx.hideToast();
                }
              } else {
                wx.hideToast();
                _this.$wuxToast.show({
                  type: 'text',
                  timer: 1500,
                  color: '#fff',
                  text: '图片上传失败，请重新选择',
                  success: () => console.log('文本内容')
                })
              }
              console.log("上传成功");
              console.log(JSON.parse(res.data));
              console.log(JSON.parse(res.data).url);
            },
            fail: function (res) {
              wx.hideToast();
              console.log("上传失败：" + res.data);
              _this.$wuxToast.show({
                type: 'text',
                timer: 1500,
                color: '#fff',
                text: '图片上传失败，请重新选择',
                success: () => console.log('文本内容')
              })
            }, complete: function () {
            }
          });
        });

      }
    })
  },
  // 提交表单按钮
  submitInfo: function () {
    var notesStr = this.data.memoInfo;
    var priceStr = this.data.matenanceCost;
    var uploadImagesArr = this.data.imagesUpload;
    var questionIdStr = this.data.questionId;
    var questionTypeNameStr = this.data.questionTypeName;
    var questionDescStr = this.data.questionDesc;

    console.log("价格：" + priceStr);
    console.log("备注：" + notesStr);
    console.log("11111+adminUserViewId:" + app.globalData.adminUserViewId);
    console.log("111111+token:" + app.globalData.token);
    
    console.log("上传图片：" + this.data.imagesUpload);

    //刷新数据
    //加载提示框
    util.showLoading();
    var that = this;
    var pages = getCurrentPages()
    // var prevPage = pages[pages.length-1]  //当前界面
    var prevPage = pages[pages.length - 2]  //上一个页面

    var urlString = app.globalData.BaseURL + '/api/task/addMaintainReport';
    var dataSource = util.json2Form({
      taskId: that.data.order_id,
      price: priceStr,
      remark: notesStr,
      uploadImages: uploadImagesArr,
      questionTypeSelect: questionIdStr,
      questionTypeName: questionTypeNameStr,
      questionDesc: questionDescStr
    });

    wx.request({
      method: "POST",
      url: urlString,
      data: dataSource,
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'adminUserViewId': app.globalData.adminUserViewId,
        'token': app.globalData.token
      },
      success: function (res) {
        util.hideToast();
        console.log("data====="+res.data);
        var code = res.data.code;
        console.log("code====="+code);
        // code = 300;
        if (code === 200) {
          that.$wuxToast.show({
            type: 'text',
            timer: 1000,
            color: '#fff',
            text: '上传成功',
            success: () => console.log('提交成功')
          });
          // 更改前一页面列表页的refreshLish属性，让其出现时刷新页面
          prevPage.setData({
            refreshLish: "true"
          });
          setTimeout(function () {
            wx.navigateBack({});
          }, 1000);
        } else {
          that.$wuxToast.show({
            type: 'text',
            timer: 1000,
            color: '#fff',
            text: res.data.msg,
            success: () => console.log('上传失败，请重新提交。')
          });
        }
      },
      fail: function () {
        that.$wuxToast.show({
          type: 'text',
          timer: 1000,
          color: '#fff',
          text: '网络错误，请稍后重试。',
          success: () => console.log('网络错误，请稍后重试。')
        })
      }, complete: function () {
        util.hideToast();
      }
    })
  },// 任务失败跳转
  taskFailedAction: function () {
    var that = this;
    wx.navigateTo({
        url: '/pages/task_failed/task_failed' + '?id=' + that.data.order_id + '&time=' + that.data.taskTime + '&address=' + that.data.taskAddress + '&task_type=' + that.data.selectedTask_type
      })
  },
    //刷新数据
    refreshNewData: function () {
      //加载提示框
      util.showLoading();
      var that = this;
      var urlStr = '/api/task/' + this.data.order_id;
      var parameters = "";
      console.log("parameters = " + parameters);
      util.request(urlStr, parameters, function (res) {
        console.log("data===" + res.data);
        util.hideToast();
        var queListStr = res.data.data.queList;
        var questionStr = res.data.data.task.content;
        var index = res.data.data.index;
        var questionIdStr = res.data.data.task.questionId;
        var questionTypeNameStr = queListStr[index].name;
        var matenanceCostStr = res.data.data.task.installFee;
        var filterBuildArrayStr = res.data.data.partsList;

        that.setData({
          questionDesc: questionStr,
          questionList: queListStr,
          questionSelectIndex: index,
          questionId: questionIdStr,
          questionTypeName: questionTypeNameStr,
          matenanceCost: matenanceCostStr,
          filterBuildArray: filterBuildArrayStr
        });

        var startTime = res.data.data.task.startTime;
        if (startTime == "" || startTime == undefined) {
          // 未开始任务，提示先开始任务
          wx.showModal({
            title: '该任务暂未开始',
            content: '请返回首页开始任务，再提交任务信息',
            cancelText: '暂不开始',
            confirmText: '立即返回',
            success: function (res) {
              if (res.confirm) {
                console.log("确认返回首页");
                wx.navigateBack({})
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }

      })
    }, complete: function () {
      util.hideToast();
    }
})